package rpc03;

import com.hl.rpc.common.User;
import com.hl.rpc.service.IUserService;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * Created by yuanhailong on 2021/10/30.
 * 客户端代理对象：屏蔽客户端访问请求时候的细节
 */
public class Stub {

    public static IUserService getStub() throws Exception{
        InvocationHandler invocationHandler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket=new Socket("localhost",9999);

                System.out.println("rpc03 动态代理...");

                /**
                 * 往服务端写入数据
                 */
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                DataOutputStream dos=new DataOutputStream(baos);
                dos.writeInt(111);
                socket.getOutputStream().write(baos.toByteArray());
                socket.getOutputStream().flush();
                /**
                 * 获取服务端数据
                 */
                DataInputStream dis=new DataInputStream(socket.getInputStream());
                int id1=dis.readInt();
                String name=dis.readUTF();
                User user=new User(id1,name);
                dos.close();
                socket.close();
                return user;
            }
        };
        //创建动态代理对象
        Object instance = Proxy.newProxyInstance(IUserService.class.getClassLoader(), new Class[]{IUserService.class}, invocationHandler);
        return (IUserService)instance;

    }

}
